package com.taomus.mytools.date.ntp;

import java.net.InetAddress;
import java.net.SocketTimeoutException;

import org.apache.commons.net.ntp.NTPUDPClient;
import org.apache.commons.net.ntp.TimeInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.taomus.mytools.helper.properties.Properties;

public class DateNTPHelper {
	private final static Logger logger = LoggerFactory.getLogger(DateNTPHelper.class);
    public static String DEFAULT_HOST = null;
    private static Long NtpbaseTimeStamp = null;
    private static Long systembaseTimeStamp = null;
    
    static{
    		DEFAULT_HOST = (String)Properties.get("ntp.server");
    }

    public static long currentTimeMillis() {
        try {
        	if (DEFAULT_HOST == null)
                  return System.currentTimeMillis();
        	if(NtpbaseTimeStamp == null){
        		NtpbaseTimeStamp = ntpCurrentTimeMillis();
        		systembaseTimeStamp = System.currentTimeMillis();
        	}
        	long cur = System.currentTimeMillis();
           return NtpbaseTimeStamp + (cur - systembaseTimeStamp);
        } catch (Exception e) {
        	 logger.error("DateNTPHelper",e);
            return System.currentTimeMillis();
        }
    }

    public static long ntpCurrentTimeMillis() throws Exception{
    	logger.info("get ntp current time millis");
    	if(DEFAULT_HOST.indexOf(",") == -1){
	    		logger.info(DEFAULT_HOST);
				NTPUDPClient nuc = new NTPUDPClient();
				InetAddress ia;
				ia = InetAddress.getByName(DEFAULT_HOST);
				nuc.setDefaultTimeout(500);
				TimeInfo timeInfo =  nuc.getTime(ia);
				return timeInfo.getMessage().getOriginateTimeStamp().getTime();
    	}else{
    		String[] hosts = DEFAULT_HOST.split(",");
    		for(String host : hosts){
    			try {
    				logger.info(host);
    				NTPUDPClient nuc = new NTPUDPClient();
    				InetAddress ia;
    				ia = InetAddress.getByName(host);
    				nuc.setDefaultTimeout(500);
    				TimeInfo timeInfo =  nuc.getTime(ia);
    				return timeInfo.getMessage().getOriginateTimeStamp().getTime();
    			} catch (SocketTimeoutException e) {
    				 logger.error("TimeoutException ",e);
    			}
    		}	
    	}
		return System.currentTimeMillis();
    }
}
